<template>
    <div class="dashboard-container">
  
      <!-- 顶部操作栏 -->
      <div>
          <el-form :inline="true" :model="params"  size="mini">
            <el-form-item>
              <el-select v-model="params.companyId" @change="handleChangeCompany" style="width: 100%;" filterable clearable placeholder="请选择公司">
                <el-option v-for="item in companyList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="params.departmentId" style="width: 100%;" filterable clearable placeholder="请选择部门">
                <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-input placeholder="请输入账号" v-model="params.loginName" clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-input placeholder="请输入姓名" v-model="params.realName" clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-input placeholder="请输入手机号" v-model="params.phone" clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" plain @click="handleSearch">
                查询
                <i class="el-icon-search"></i>
              </el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleAdd('create')" size="mini">
                <i class="el-icon-plus"></i>
                  新增
              </el-button>
            </el-form-item>
          </el-form>
      </div>
  
      <!-- 内容栏 -->
      <div class="body">
  
        <!-- 列表 -->
        <el-table :data="list" v-loading="loading">
          <el-table-column label="真实姓名" prop="realName"></el-table-column>
          <el-table-column label="公司" prop="company.name"></el-table-column>
          <el-table-column label="部门" prop="department.name"></el-table-column>
          <el-table-column label="账号" prop="loginName"></el-table-column>
          <el-table-column label="手机号" prop="phone"></el-table-column>
          <el-table-column label="有效期" prop="expireTimeTimeName"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="{row}">
              <el-tag type="success" v-if="row.enabled==1">正常</el-tag>
              <el-tag type="danger" v-else>禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="230px">
            <template slot-scope="{row}">
              <el-button type="text" @click="handleAdd('update', row)">
                <i class="el-icon-edit-outline"></i>
                编辑
              </el-button>
              <el-button type="text danger" @click="handleDelete(row.id)">删除</el-button>
              <el-button type="text" @click="handleEnable(row.id, 1)" v-if="row.enabled!=1">启用</el-button>
              <el-button type="text danger" @click="handleEnable(row.id, 0)" v-else>禁用</el-button>
              <el-button type="text danger" @click="handleRestPass(row.id)">重置密码</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="page">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="params.pageIndex+1"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="params.pageCount"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
  
      </div>
  
      <!-- 新增、编辑 -->
      <el-dialog 
        top="50px"
        :visible="dialogVisible" 
        :close-on-click-modal="false"
        @close="dialogVisible=false"
        :title="dialogType=='create'?'创建用户':'编辑用户'"
        width="600px"
      >
        <el-form ref="form" :rules="rules" :model="temp" size="mini">
          <el-form-item prop="companyId" label="公司" v-if="!temp.is_son">
            <el-select @change="handleChangeCompany" v-model="temp.companyId" placeholder="请选择公司" style="width: 100%;">
                <el-option v-for="item in companyList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择部门" prop="departmentId">
            <el-select v-model="temp.departmentId" style="width: 100%;" filterable clearable>
              <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="真实姓名" prop="realName">
            <el-input placeholder="请输入真实姓名" v-model="temp.realName"></el-input>
          </el-form-item>
          <el-form-item label="登录账号" prop="loginName">
            <el-input placeholder="请输入登录账号" v-model="temp.loginName"></el-input>
          </el-form-item>
          <el-form-item label="密码" v-if="dialogType=='create'">
            <el-input placeholder="请输入密码,不输入则默认手机号为密码" v-model="password"></el-input>
          </el-form-item>
          <!-- <el-form-item label="选择角色" prop="name">
            <el-select v-model="temp.role" style="width: 100%;">
              <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="手机号" prop="phone">
            <el-input placeholder="请输入手机号" v-model="temp.phone"></el-input>
          </el-form-item>
          <el-form-item label="有效期" prop="expireTime">
            <el-date-picker
              v-model="temp.expireTime"
              type="date"
              placeholder="选择日期"
              style="width: 100%;"
              value-format="timestamp"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submit('form')">提交</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
  
    </div>
  </template>
  
  <script>
  import { mapGetters } from 'vuex'
  import { userCreate, userUpdate, userGetList, userDelete, userResetPassword } from '@/api/user'
  import { departmentGetList } from '@/api/department'
  import { companyGetList } from '@/api/company';
  import moment from 'moment'
  
  export default {
    name: 'Staffuser',
    computed: {
      ...mapGetters([
        'name'
      ])
    },
    data(){
      return {
        rules: {
          realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
          departmentId: [{ required: true, message: '请选择部门', trigger: 'blur' }],
          companyId: [{ required: true, message: '请选择公司', trigger: 'blur' }],
          expireTime: [{ required: true, message: '请选择有效期', trigger: 'blur' }],
          loginName: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
          phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        },
        params: {
          enabled: '',
          companyId: '',
          userId: '',
          pageCount: 10,
          pageIndex: 1,
          phone: '',
          realName: '',
          type: 2, // 1员工 2客户
        },
        total: 0,
        list: [],
        dialogVisible: false,
        dialogType: 'create',
        temp: {
          realName: '',
          companyId: '',
          type: 2, //客户
          departmentId: '',
          expireTime: '',
          loginName: '',
          phone: '',
        },
        loading: false,
        roleList: [],  // 部门列表
        companyList: [], // 公司列表
        password: '',
      }
    },
    mounted(){
      this.handleSearch();
      this.getCompany();
    },
  
    methods:{
      //修改公司选择
      handleChangeCompany(val){
        if(val){
          this.getDepartment(val);
        }else{
          this.roleList = [];
          this.params.departmentId = '';
        }
        
      },
      //获取公司列表
      async getCompany(){
        let data = await companyGetList({ pageCount: 9999, userType: 2 });
        this.companyList = data.list.map(item=>{
            return { label: item.name, value: item.id }
        })
      },
      // 禁用启用
      async handleEnable(id, enabled){
        await userUpdate({ id, enabled })
        this.$message.success({ message: '操作成功' })
        this.getData();
      },
      // 获取部门列表
      async getDepartment(val){
        let data = await departmentGetList({companyId: val,pageCount: 1000,pageIndex: 0})
        this.roleList = data.list.map(item=>{
          return { label: item.name, value: item.id }
        })
      },
      //重置密码
      async handleRestPass(id){
        this.$prompt('请输入密码', '重置密码', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(async ({ value }) => {
          // coding...
          await userResetPassword({ id, password: md5(value).toUpperCase() })
          this.$message.success({ message: '重置成功' })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });       
        });
        
      },
      // 点击删除
      handleDelete(id){
        this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await userDelete({ id })
          this.getData();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      //提交表单
      submit(formName){
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            let temp = JSON.parse(JSON.stringify(this.temp))
            
            if(this.dialogType =='create'){
              if(this.password){
                temp.password = md5(this.password).toUpperCase();
              }
              await userCreate(temp)
              this.$message.success('创建成功')
            }else{
              await userUpdate(temp)
              this.$message.success('修改成功')
            }
            this.handleSearch();
            this.dialogVisible = false;
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 点击新增、编辑
      handleAdd(type, row){
        this.dialogType = type;
        this.dialogVisible = true;
        this.password = '';
        if(type=='create'){
          this.temp = {
            realName: '',
            companyId: '',
            type: 2,
            departmentId: '',
            entryTime: '',
            loginName: '',
            phone: ''
          }
        }else{
          this.temp = JSON.parse(JSON.stringify(row))
          this.getDepartment(this.temp.companyId)
        }
        
      },
      //修改搜索条件
      handleSearch(){
        this.params.pageIndex = 0;
        this.getData();
      },
      //加载列表数据
      async getData(){
        this.loading = true
        let data = await userGetList(this.params)
        this.loading = false;
        this.total = data.totalCount;
        this.list = data.list.map(item=>{
          item.createTime = moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')
          item.expireTime = item.expireTime>0?item.expireTime:""
          item.expireTimeTimeName = item.expireTime>0?moment(item.expireTime).format('YYYY-MM-DD'):"已到期"
          return item;
        });
      },
      // 修改每页数量
      handleSizeChange(val){
        this.params.pageIndex = 0;
        this.params.pageCount = val;
        this.getData();
      },
      // 切换分页
      handleCurrentChange(val){
        this.params.pageIndex = val - 1;
        this.getData();
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .dashboard {
    &-container {
      margin: 30px;
      position: relative;
      .search{
        overflow: hidden;
        margin-bottom: 10px;
      }
      .page{
        padding: 20px 0;
        text-align: center;
      }
    }
    &-text {
      font-size: 30px;
      line-height: 46px;
    }
  }
  </style>
  